var express = require('express');
var router = express.Router();
var User = require('./../sql/collection/users');
var sql = require('./../sql');
var utils = require('./../utils')
var uuid = require('node-uuid');
var bcrypt = require('bcryptjs');
var jwt = require('jsonwebtoken');
var salt = bcrypt.genSaltSync(10);


/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

// 实现注册接口 -- post提交方式
router.post('/register', (req, res, next) => {
  let { username, password, tel } = req.body;
  sql.find(User, { tel }, { _id: 0 }).then(data => {
    if (data.length === 0) {
      let userid = 'users_' + uuid.v1();
      password = bcrypt.hashSync(password, salt)
      console.log(password);
      
      sql.insert(User, { userid, username, password, tel}).then(() => {
        res.send(utils.registersuccess)
      })
    } else {
      res.send(utils.registered)
    }
  })
})


// 实现登陆功能
router.post('/login', (req, res, next) => {
  let { tel, password } = req.body;
  sql.find(User, { tel }, { _id: 0 }).then(data => {
    if (data.length === 0) {
      res.send(utils.unregister)
    } else {
      let pwd = data[0].password;
      var flag = bcrypt.compareSync(password, pwd)
      if (flag) {
        let userid = data[0].userid
        let username = data[0].username
        let token = jwt.sign({ userid }, 'vuexiangmu4', {
          expiresIn: 60*60*24*7// 授权时效7天
        })
        res.send({
          code: '10010',
          message: '登陆成功',
          token: token,
          userid,
          username
        })
      } else {      
        res.send({
          code: '10100',
          message: '密码错误'
        })
      }
    }
  })
})

//查询用户信息
router.post('/userselect', (req, res, next) => {
  let { userid  } = req.body;
  sql.find(User, { userid }, { _id: 0 }).then(data => {
    if (data.length === 0) {
        res.send({
          code: '40000',
          message: '无该用户信息'
        })
    } else {
      res.send({
        code: '200',
        message: '查询用户信息',
        data
      })
    }
  })
})
router.post('/updatepassword', (req, res, next) => {
  let { userid, password } = req.body;
  password = bcrypt.hashSync(password, salt)
  sql.update(User, { userid }, { $set: {password: password} }).then(data => {
      res.send({
        code: '200',
        message: '密码修改成功'
      })
  })
})
module.exports = router;
